<template>
  <div class="cu-common-layout">
    <div class="cu-common-layout-center">
      <el-row class="cu-common-search-box" :gutter="16">
        <el-form @submit.native.prevent>
          <el-col :span="6">
            <el-form-item label="开业日期">
              <el-date-picker v-model="pickerVal" type="daterange" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions" value-format="yyyy-MM-dd" clearable :editable="false"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="校区品牌">
              <el-select v-model="query.brand" placeholder="请选择" clearable>
                <!-- 修正为使用 enCode 作为值，避免 id 不一致导致查询失败 -->
                <el-option v-for="item in brandOptions" :key="item.enCode" :label="item.fullName" :value="item.enCode" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="开业校区">
              <el-select v-model="query.campusId" placeholder="请选择" clearable filterable>
                <el-option v-for="item in campusOptions" :key="item.id" :label="item.fullName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="管理区域">
              <el-select v-model="query.area" placeholder="请选择" clearable>
                <!-- 修正 label 字段为 fullName，与字典结构保持一致 -->
                <el-option v-for="item in companyOptions" :key="item.enCode" :label="item.fullName" :value="item.enCode" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否达标">
              <el-select v-model="query.isQualified" placeholder="请选择" clearable>
                <el-option label="是" :value="true" />
                <el-option label="否" :value="false" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="审核状态">
              <el-select v-model="query.flowState" placeholder="请选择审核状态" filterable clearable>
                <el-option key="" label="全部" value="" />
                <el-option key="0" label="等待提交" value="0" />
                <el-option key="1" label="等待审核" value="1" />
                <el-option key="2" label="审核通过" value="2" />
                <el-option key="3" label="审核驳回" value="3" />
                <el-option key="4" label="流程撤回" value="4" />
                <el-option key="5" label="审核终止" value="5" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="辅导师">
              <el-input v-model="query.instructor" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="预计回访日期">
              <el-date-picker v-model="followPickerVal" type="daterange" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions" value-format="yyyy-MM-dd" clearable :editable="false"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="search()">{{ $t('common.search') }}</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div class="cu-common-layout-main cu-flex-main" v-loading="listLoading" element-loading-text="加载中..." element-loading-spinner="el-icon-loading" element-loading-background="rgba(255,255,255,0.6)">
        <div class="cu-common-head">
          <div class="cu-common-head-left">
            <el-button v-has="'btn_add'" type="primary" icon="el-icon-plus" @click="addOrUpdateHandle()">新增</el-button>
            <el-button type="default" icon="el-icon-setting" style="margin-left: 8px" @click="openThresholdDialog">阈值配置</el-button>
          </div>
          <div class="cu-common-head-right">
            <el-tooltip effect="dark" content="刷新" placement="top">
              <el-link icon="icon-ym icon-ym-Refresh cu-common-head-icon" :underline="false" @click="refresh()" />
            </el-tooltip>
            <screenfull is-container />
          </div>
        </div>
        <custom-table :data="list" :loading="listLoading" border>
          <el-table-column prop="createTime" label="提交时间" width="120" align="center" :formatter="custom.tableDateTimeFormat" />
          <el-table-column prop="createUserName" label="提交人" width="100" align="center" />
          <el-table-column label="校区品牌" width="80" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.campusBrand | dynamicCodeText(brandOptions) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="campusName" label="校区名称" width="200" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              <el-link v-if="scope.row.flowState" type="primary" :underline="false" @click="addOrUpdateHandle(scope.row.id, scope.row.flowState)">
                {{ scope.row.campusName }}
              </el-link>
              <span v-else>{{ scope.row.campusName }}</span>
            </template>
          </el-table-column>
          <!-- 新增：开业类型 -->
          <el-table-column prop="openingType" label="开业类型" width="120" align="center">
            <template slot-scope="scope">
              <span>{{ openingTypeText(scope.row.openingType) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="openingDate" label="开业日期" width="120" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.openingDate | dateFormat }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="expectedFollowUpDate" label="预计回访日期" width="140" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.expectedFollowUpDate | dateFormat }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="guidanceDates" label="辅导天数" width="100" align="center">
            <template slot-scope="scope">
              <el-tooltip effect="dark" placement="top" :enterable="false" :dangerouslyUseHTMLString="true">
                <div slot="content" v-html="formatGuidanceDatesTooltip(scope.row.guidanceDates)"></div>
                <span>{{ formatGuidanceDatesCount(scope.row.guidanceDates) }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="instructorName" label="辅导师" width="100" align="center" />
          <!-- 新增：学位数与床位数（调整顺序到最前） -->
          <el-table-column prop="degreeCount" label="学位数" width="100" align="center" />
          <el-table-column prop="bedCount" label="床位数" width="100" align="center" />
          <!-- 调整：托管总人数 -->
          <el-table-column prop="totalCareCount" label="招生人数（开业）" width="120" align="center" />
          <el-table-column label="招生人数（回访）" width="120" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.followUp && scope.row.followUp.totalCareCount }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="totalOperationScore" label="校长能力评分" width="120" align="center" />

          <el-table-column prop="isPass" label="是否及格" width="100" align="center">
            <template slot-scope="scope">
              <el-tag :type="scope.row.isPass ? 'success' : 'danger'">{{ scope.row.isPass ? '是' : '否' }}</el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="isQualified" label="是否达标" width="100" align="center">
            <template slot-scope="scope">
              <el-tag :type="scope.row.isQualified ? 'success' : 'danger'">{{ scope.row.isQualified ? '是' : '否' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="flowState" label="审核状态" align="center" width="100">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.flowState == 1">等待审核</el-tag>
              <el-tag v-else-if="scope.row.flowState == 2" type="success">审核通过</el-tag>
              <el-tag v-else-if="scope.row.flowState == 3" type="danger">审核驳回</el-tag>
              <el-tag v-else-if="scope.row.flowState == 4" type="danger">流程撤回</el-tag>
              <el-tag v-else-if="scope.row.flowState == 5" type="warning">审核终止</el-tag>
              <el-tag v-else type="info">等待提交</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="280" align="center">
            <template slot-scope="scope">
              <el-button type="text" v-has="'btn_edit'" :disabled="[1, 2, 5].indexOf(scope.row.flowState) > -1" @click="addOrUpdateHandle(scope.row.id)">编辑</el-button>
              <el-button type="text" v-has="'btn_remove'" :disabled="[1, 2, 3, 5].indexOf(scope.row.flowState) > -1" @click="handleDel(scope.row.id)" class="cu-table-delBtn">删除</el-button>
              <el-button size="mini" type="text" :disabled="!scope.row.flowState" @click="addOrUpdateHandle(scope.row.id, scope.row.flowState)" v-has="'btn_detail'">详情</el-button>
              <el-button v-if="!scope.row.followUp && canFollowUp(scope.row)" type="text" size="mini" :disabled="!canFollowUp(scope.row)" @click="handleFollowUpAction(scope.row, 'add')" v-has="'btn_followup'">
                <i class="el-icon-plus" style="margin-right: 2px"></i>
                回访
              </el-button>
              <el-button v-if="scope.row.followUp" type="text" size="mini" @click="handleFollowUpAction(scope.row, 'edit')" v-has="'btn_followup'" style="color: #E6A23C;">
                <i class="el-icon-edit" style="margin-right: 2px"></i>
                编辑回访
              </el-button>
              <el-button v-if="scope.row.followUp" type="text" size="mini" @click="handleFollowUpAction(scope.row, 'view')" style="color: #409eff">
                <i class="el-icon-view" style="margin-right: 2px"></i>
                回访详情
              </el-button>
            </template>
          </el-table-column>
        </custom-table>
        <pagination :total="total" :page.sync="listQuery.currentPage" :limit.sync="listQuery.pageSize" @pagination="initData" />
      </div>
      <!-- 阈值配置对话框 -->
      <el-dialog :visible.sync="thresholdDialogVisible" title="开业辅导阈值配置" width="420px">
        <el-form :model="thresholdForm" :rules="thresholdRules" ref="thresholdFormRef" label-width="120px">
          <el-form-item label="及格线(人数)" prop="passThreshold">
            <el-input-number v-model="thresholdForm.passThreshold" :min="0" :max="9999" />
          </el-form-item>
          <el-form-item label="达标线(人数)" prop="standardThreshold">
            <el-input-number v-model="thresholdForm.standardThreshold" :min="0" :max="9999" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="thresholdDialogVisible=false">取 消</el-button>
          <el-button type="primary" :loading="thresholdLoading" @click="saveThresholds">保 存</el-button>
        </template>
      </el-dialog>
    </div>
    <FlowBox v-if="flowVisible" ref="Form" @close="colseFlow" />
    <follow-up-dialog v-if="followUpVisible" ref="followUpDialog" :current-row="currentRow" :edit-data="editFollowUpData" :is-detail="isFollowUpDetail" @refresh="refresh" @close="closeFollowUp" />
  </div>
</template>

<script>
import FlowBox from '@/views/workFlow/components/FlowBox'
import { getCampusSelector } from '@/api/campus/campus'
import { DICTIONARY_TYPES, getBatchDictionaryData } from '@/utils/dictionaryConstants'
import { getGuidanceList } from '@/api/campus/guidance'
import { getGuidanceThreshold, updateGuidanceThreshold } from '@/api/campus/guidance'
import FollowUpDialog from './flowup/index.vue'
export default {
  name: 'CampusGuidance',
  components: { FlowBox, FollowUpDialog },
  data() {
    return {
      query: {
        brand: undefined,
        campusId: undefined,
        openingDate: undefined,
        instructor: undefined,
        isQualified: undefined,
        area: undefined,
        expectedFollowUpDate: undefined,
        flowState: undefined
      },
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      pickerVal: [],
      followPickerVal: [],
      list: [],
      listLoading: true,
      total: 0,
      listQuery: {
        currentPage: 1,
        pageSize: 20,
        sort: 'desc',
        sidx: 'createTime'
      },
      // 阈值配置对话框状态
      thresholdDialogVisible: false,
      thresholdLoading: false,
      thresholdForm: { passThreshold: 20, standardThreshold: 30 },
      thresholdRules: {
        passThreshold: [
          { required: true, message: '请输入及格线人数', trigger: 'change' },
          { validator: (r,v,cb)=> (Number(v)>=0 ? cb() : cb(new Error('及格线必须为非负数'))), trigger: 'change' }
        ],
        standardThreshold: [
          { required: true, message: '请输入达标线人数', trigger: 'change' },
          { validator: (r,v,cb)=> (Number(v)>=Number((this.thresholdForm||{}).passThreshold) ? cb() : cb(new Error('达标线不得小于及格线'))), trigger: 'change' }
        ]
      },
      currentRow: null,
      currentFollowUpDetail: null,
      followUpDetailVisible: false,
      followUpVisible: false,
      flowVisible: false,
      editFollowUpData: null,
      campusOptions: [],
      brandOptions: [],
      companyOptions: []
    }
  },
  filters: {
    flowStateType(state) {
      const typeMap = {
        0: 'info',
        1: 'warning',
        2: 'success',
        3: 'danger'
      }
      return typeMap[state] || 'info'
    },
    flowStateText(state) {
      const textMap = {
        0: '草稿',
        1: '审核中',
        2: '已通过',
        3: '已拒绝'
      }
      return textMap[state] || '未知'
    },
    currency(value) {
      if (!value) return '0.00'
      return Number(value).toLocaleString('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      })
    },
    // 新增日期格式化过滤器，默认格式 YYYY-MM-DD，可传自定义格式
    dateFormat(value, fmt = 'YYYY-MM-DD') {
      if (!value) return ''
      let date
      if (typeof value === 'number' || /^\d+$/.test(value)) {
        // 纯数字按时间戳（毫秒）处理
        date = new Date(Number(value))
      } else if (typeof value === 'string') {
        // 字符串替换连字符，避免 Safari 等解析问题
        const normalized = value.replace(/-/g, '/')
        date = new Date(normalized)
      } else if (value instanceof Date) {
        date = value
      } else {
        return ''
      }
      if (isNaN(date.getTime())) return ''
      const pad = n => (n < 10 ? '0' + n : '' + n)
      const YYYY = date.getFullYear()
      const MM = pad(date.getMonth() + 1)
      const DD = pad(date.getDate())
      const HH = pad(date.getHours())
      const mm = pad(date.getMinutes())
      const ss = pad(date.getSeconds())
      return fmt
        .replace('YYYY', YYYY)
        .replace('MM', MM)
        .replace('DD', DD)
        .replace('HH', HH)
        .replace('mm', mm)
        .replace('ss', ss)
    }
  },
  async created() {
    // 优先加载数据字典，确保过滤器与选择项可用
    await this.loadDictionaryData()
    // 加载校区下拉选项
    getCampusSelector({ brand: this.query.brand }).then(res => {
      this.campusOptions = res.data
    })
    // 初始化列表数据
    this.initData()
  },
  methods: {
    /**
     * 打开阈值配置对话框（北京时间：2025-11-17）
     * 行为：加载当前阈值；失败时提示并保留默认值
     */
    async openThresholdDialog() {
      try {
        this.thresholdLoading = true
        const resp = await getGuidanceThreshold()
        const payload = (resp && resp.data) || resp || {}
        if (payload && typeof payload.passThreshold === 'number') {
          this.thresholdForm.passThreshold = payload.passThreshold
        }
        if (payload && typeof payload.standardThreshold === 'number') {
          this.thresholdForm.standardThreshold = payload.standardThreshold
        }
      } catch (e) {
        this.$message.error('阈值加载失败')
      } finally {
        this.thresholdLoading = false
        this.thresholdDialogVisible = true
      }
    },
    /**
     * 保存阈值配置（北京时间：2025-11-17）
     * 行为：校验表单→提交更新→成功提示并关闭对话框
     */
    saveThresholds() {
      this.$refs.thresholdFormRef.validate(async valid => {
        if (!valid) return
        try {
          this.thresholdLoading = true
          await updateGuidanceThreshold({
            passThreshold: Number(this.thresholdForm.passThreshold),
            standardThreshold: Number(this.thresholdForm.standardThreshold)
          })
          this.$message.success('阈值更新成功')
          this.thresholdDialogVisible = false
        } catch (e) {
          this.$message.error('阈值更新失败')
        } finally {
          this.thresholdLoading = false
        }
      })
    },
    // 开业类型文本映射
    openingTypeText(type) {
      if (!type) return '-'
      const map = { new: '新校开业', multi: '多校自主开业' }
      return map[type] || '-'
    },
    // 辅导日期计数显示，如 "3 天"
    formatGuidanceDatesCount(dates) {
      if (!dates) return '-'
      let arr = []
      if (Array.isArray(dates)) arr = dates
      else if (typeof dates === 'string') arr = dates.split(',').filter(Boolean)
      else return '-'
      const count = arr.length
      return count ? `${count} 天` : '-'
    },
    // 辅导日期 tooltip 内容，按行展示日期
    formatGuidanceDatesTooltip(dates) {
      // 如果没有日期数据，直接返回提示文本
      if (!dates) return '无辅导日期'

      // 统一处理日期数组
      const dateArray = Array.isArray(dates) ? dates : typeof dates === 'string' ? dates.split(',').filter(date => date && date.trim()) : []

      // 格式化每个日期并用HTML标签实现换行
      return dateArray.length > 0 ? dateArray.map(date => this.$options.filters.dateFormat(date)).join('<br/>') : '无辅导日期'
    },
    // 午/晚/全托人数合并显示，如 "午10/晚8/全12"

    // 初始化数据
    initData() {
      this.listLoading = true
      let _query = {
        ...this.listQuery,
        ...this.query
      }
      let query = {}
      for (let key in _query) {
        if (Array.isArray(_query[key])) {
          query[key] = _query[key].join()
        } else {
          query[key] = _query[key]
        }
      }
      getGuidanceList(query)
        .then(res => {
          const data = res.data || {}
          this.list = data.list || []
          this.total = data.pagination && data.pagination.total ? data.pagination.total : data.total || 0
          this.listLoading = false
        })
        .catch(err => {
          this.$message.error('列表查询失败，请稍后重试')
          this.listLoading = false
        })
    },

    // 删除处理
    handleDel(id) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        type: 'warning'
      })
        .then(() => {
          request({
            url: `/api/campus/guidance/${id}`,
            method: 'DELETE'
          }).then(res => {
            this.$message({
              type: 'success',
              message: res.msg,
              onClose: () => {
                this.initData()
              }
            })
          })
        })
        .catch(() => {})
    },
    addOrUpdateHandle(id, flowState) {
      let data = {
        id: id || '',
        enCode: 'guidance',
        flowId: '742235129719554117',
        formType: 1,
        opType: flowState ? 0 : '-1',
        status: flowState
      }
      this.flowVisible = true
      this.$nextTick(() => {
        this.$refs.Form.init(data)
      })
    },

    // 搜索
    search() {
      if (this.pickerVal && this.pickerVal.length) {
        this.query.openingDate = [this.pickerVal[0], this.pickerVal[1]].join(',')
      } else {
        this.query.openingDate = ''
      }
      if (this.followPickerVal && this.followPickerVal.length) {
        this.query.expectedFollowUpDate = [this.followPickerVal[0], this.followPickerVal[1]].join(',')
      } else {
        this.query.expectedFollowUpDate = ''
      }

      this.listQuery = {
        currentPage: 1,
        pageSize: 20,
        sort: 'desc',
        sidx: 'createTime'
      }
      this.initData()
    },

    // 刷新
    refresh() {
      this.query = {
        brand: undefined,
        campusId: undefined,
        openingDate: undefined,
        instructor: undefined,
        isQualified: undefined,
        area: undefined,
        expectedFollowUpDate: undefined,
        flowState: undefined
      }
      this.listQuery = {
        currentPage: 1,
        pageSize: 20,
        sort: 'desc',
        sidx: 'createTime'
      }
      this.initData()
    },

    // 关闭流程
    colseFlow(isrRefresh) {
      this.flowVisible = false
      if (isrRefresh) this.refresh()
    },

    // 加载数据字典数据
    async loadDictionaryData() {
      try {
        const dictionaries = await getBatchDictionaryData([DICTIONARY_TYPES.BRAND, DICTIONARY_TYPES.COMPANY], true)
        const rawBrand = dictionaries && dictionaries[DICTIONARY_TYPES.BRAND] ? dictionaries[DICTIONARY_TYPES.BRAND] : []
        const rawCompany = dictionaries && dictionaries[DICTIONARY_TYPES.COMPANY] ? dictionaries[DICTIONARY_TYPES.COMPANY] : []
        this.brandOptions = rawBrand.filter(item => item.enabledMark === 1)
        this.companyOptions = rawCompany.filter(item => item.enabledMark === 1)
      } catch (error) {
        console.error('[Guidance] 加载数据字典失败:', error)
        this.$message.error('加载数据字典失败')
      }
    },

    // 判断是否可以添加回访
    canFollowUp(row) {
      return !!row.openingDate && row.flowState === 2
    },

    /**
     * 统一处理回访操作（新增、编辑、查看详情）
     * @param {Object} row 当前行数据
     * @param {String} mode 操作模式：'add'=新增, 'edit'=编辑, 'view'=查看详情
     */
    handleFollowUpAction(row, mode = 'add') {
      // 检查编辑和查看详情模式下是否有回访数据
      if ((mode === 'edit' || mode === 'view') && !row.followUp) {
        this.$message.warning('该记录暂无回访信息')
        return
      }

      // 设置当前行数据
      this.currentRow = row

      // 设置模式
      this.isFollowUpDetail = mode === 'view'
      this.editFollowUpData = mode === 'edit' ? row.followUp : null

      // 显示对话框
      this.followUpVisible = true

      // 调用子组件方法
      this.$nextTick(() => {
        const isEdit = mode === 'edit'
        const isDetailMode = mode === 'view'

        if (this.$refs.followUpDialog) {
          this.$refs.followUpDialog.showFollowUpDialog(row, isEdit, isDetailMode, row.followUp)
        }
      })
    },
    /**
     * 统一关闭对话框方法
     * @param {Boolean} isRefresh 是否需要刷新数据
     * @param {String} type 对话框类型：'followUp'=回访对话框, 'detail'=详情对话框
     */
    closeDialog(isRefresh = false, type = 'followUp') {
      if (type === 'followUp') {
        this.followUpVisible = false
        this.isFollowUpDetail = false
      } else if (type === 'detail') {
        this.detailVisible = false
        this.detailData = null
      }

      // 如果需要刷新数据，则调用reset方法
      if (isRefresh) {
        this.reset()
      }
    },

    // 关闭回访对话框 (兼容旧代码调用)
    closeFollowUp(isrRefresh) {
      this.closeDialog(isrRefresh, 'followUp')
    },
    // 查看回访详情
    viewFollowUpDetail(row) {
      this.handleFollowUpAction(row, 'view')
    },
    // 关闭详情页面
    closeDetail() {
      this.closeDialog(false, 'detail')
    }
  }
}
</script>
